package com.dazzle.core.web.servlet;

import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.dazzle.core.util.common.AppUtil;
import com.dazzle.system.entity.SysImages;
import com.dazzle.system.service.SysImagesService;


@SuppressWarnings("serial")
public class ImageUploadServlet extends HttpServlet {
	private ServletConfig servletConfig=null;
	private SysImagesService sysImagesService=(SysImagesService)AppUtil.getBean("sysImagesService");
	private String uploadPath=""; // 上传文件的目录   
	private String tempPath=""; // 临时文件目录 
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
        File tempfile=new File(tempPath);//上传缓存临时文件夹
        if(!tempfile.exists()){
            tempfile.mkdir();
        }
        req.setCharacterEncoding("UTF-8");
		resp.setCharacterEncoding("UTF-8");
		
		//判断是否上传文件表单,也就是form中是否有enctype="multipart/form-data"项;必须post提交,get提交对内容长度有限制
        if(ServletFileUpload.isMultipartContent(req)){
            DiskFileItemFactory factory=new DiskFileItemFactory();
            factory.setSizeThreshold(1024*512);//设置缓冲区大小
            factory.setRepository(tempfile);//设置临时文件夹
            ServletFileUpload fileUpload=new ServletFileUpload(factory);
            fileUpload.setFileSizeMax(10*1024*1024);//设置最大文件大小
            
            try {
                @SuppressWarnings("unchecked")
                List<FileItem> items=fileUpload.parseRequest(req);//获取所有表单
                for(FileItem item:items){
                    //判断当前的表单控件是否是一个普通控件
                    if(!item.isFormField()){
                        //是一个文件控件时
                        String name=item.getName();
                        System.out.println("上传文件名:"+name);
                        System.out.println("文件大小:"+getStrFileSize(item.getSize()));
                        
                        String extName=name.substring(name.lastIndexOf("."));
                        String newName=new SimpleDateFormat("yyyyMMDDHHmmssms").format(new Date());
                        String childName = newName+"_100x100";
                        System.out.println("扩展名"+extName);
                        
                        String imgPath = uploadPath+"/"+newName+extName;
                        String childPath = uploadPath+"/"+childName+extName;
                        //只能存相对路径,取的时候绝对路径拒绝访问
                        String revImgPath = "attachFiles/"+newName+extName;
                        String revChildPath = "attachFiles/"+childName+extName;
                        
//                        //临时测试路径,后面要删除
//                        String imgPath2 = uploadPath2+"/"+newName+extName;
//                        String childPath2 = uploadPath2+"/"+childName+extName;
//                        item.write(new File(imgPath2));
//                        cutImage(imgPath2,childPath2);
                        
                        item.write(new File(imgPath));
                        
                        
                        //截100X100的小图
                        cutImage(imgPath,childPath);
                        
                        
                        //保存图片信息
                        SysImages images = new SysImages();
                        images.setImgExt(extName);
                        images.setImgName(name);
                        images.setImgSize(getStrFileSize(item.getSize()));
                        images.setUploadDate(new Date());
                        images.setImgPath(revImgPath);
                        images.setImgDesc("test");
                        images.setImgChildpath(revChildPath);
                        sysImagesService.save(images);
                    }else{
                        //是普通控件时
                        String desc=item.getString("UTF-8");
                        System.out.println("文件描述"+desc);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else{
            throw new RuntimeException("请设置form表单的enctype属性");
        }
        resp.sendRedirect("system/images_list.do");
	}
	
	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		this.servletConfig=config;
	}
	public void init() throws ServletException {
		   
		//初始化上传的路径及临时文件路径
		
		//uploadPath=getServletContext().getRealPath("/attachFiles/");
		
		//临时测试目录,到时要删除
		uploadPath="D:/workspace40/dazzle/src/main/webapp/attachFiles";
		
	    File uploadPathFile=new File(uploadPath);
	    if(!uploadPathFile.exists()){
	    	uploadPathFile.mkdirs();
	    }
	    tempPath=uploadPath+"/temp";
	    
	    File tempPathFile=new File(tempPath); 
	    if(!tempPathFile.exists()){
	    	tempPathFile.mkdirs();
	    }
	}
	private String getStrFileSize(double size){
	    DecimalFormat df=new DecimalFormat("0.00");
		if(size>1024*1024){
			 double ss=size/(1024*1024);
		 	 return df.format(ss)+" M";
		}else if(size>1024){
			double ss=size/1024;
			return df.format(ss)+" KB";
		}else{
			return size+" bytes";
		}
    }
	
	public  void cutImage(String imgSrc, String imgDist) {
		try {
			File file = new File(imgSrc);
			if (!file.exists()) {
				System.out.print("no picture!");
				return;
			}
			InputStream is = new FileInputStream(file);
			OutputStream os = new FileOutputStream(imgDist);
			//scaleImage(is, os, scale);
			cutImage(is,os,0,0);
			is.close();
			os.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public  void cutImage(InputStream imgInputStream, OutputStream imgOutputStream,int x,int y) {
		try {

			Image src = javax.imageio.ImageIO.read(imgInputStream);
			
			int width2 = (int) src.getWidth(null);
			int height2 = (int) src.getHeight(null);
			BufferedImage bufferedImage = null;
			ImageFilter cropFilter; 
			Image img ;
			int dest = 0;
			// 四个参数分别为图像起点坐标和宽高 
			// 即: CropImageFilter(int x,int y,int width,int height) 
			if(width2>height2){
				dest = height2;
				cropFilter = new CropImageFilter(x, y, dest, dest*3/4); 
				img = Toolkit.getDefaultToolkit().createImage( new FilteredImageSource(src.getSource(), cropFilter));
			}else{
				dest = width2;
				cropFilter = new CropImageFilter(x, y, dest, dest*3/4); 
				img = Toolkit.getDefaultToolkit().createImage( new FilteredImageSource(src.getSource(), cropFilter));
			}
			bufferedImage = new BufferedImage(260, 180, BufferedImage.TYPE_INT_RGB);
			bufferedImage.getGraphics().drawImage(img.getScaledInstance(260, 180, Image.SCALE_SMOOTH), 0, 0, null);
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(imgOutputStream);
			encoder.encode(bufferedImage);
			System.out.print("done!");
		} catch (IOException e) {
			System.out.print("something wrong!");
			e.printStackTrace();
		}
	}
}
